<template>
  <div class="health-home-container">
    <h2 class="health-home-title">健康管理</h2>
    
    <div v-if="visibleHealthData.length > 0" class="health-overview">
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in visibleHealthData" :key="item.typeId">
          <el-card 
            class="health-card" 
            shadow="hover"
            :class="{'abnormal-card': item.isAbnormal}"
          >
            <div class="health-card-header">
              <div class="health-type">
                <i :class="getTypeIcon(item.typeId)" class="type-icon"></i>
                <span>{{ item.typeName }}</span>
              </div>
              <el-tag :type="item.isAbnormal ? 'danger' : 'success'" size="small">
                {{ item.isAbnormal ? '异常' : '正常' }}
              </el-tag>
            </div>
            <div class="health-value">
              {{ item.lastValue }} <span class="unit">{{ item.unit }}</span>
            </div>
            <div class="health-date">
              最近记录: {{ item.lastDate }}
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div v-else class="empty-data-container">
      <el-empty description="暂无健康数据">
        <template #description>
          <div>
            <p>暂无健康数据，请点击下方按钮记录您的健康数据</p>
          </div>
        </template>
        <el-button type="primary" @click="goToRecord">记录健康数据</el-button>
      </el-empty>
    </div>
    
    <div class="health-actions">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover" class="action-card" @click="goToRecord">
            <el-icon class="action-icon"><Plus /></el-icon>
            <div class="action-title">记录健康数据</div>
            <div class="action-desc">记录您的日常健康数据</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="action-card" @click="goToHistory">
            <el-icon class="action-icon"><List /></el-icon>
            <div class="action-title">健康数据历史</div>
            <div class="action-desc">查看历史健康记录和趋势</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="action-card" @click="goToReminder">
            <el-icon class="action-icon"><AlarmClock /></el-icon>
            <div class="action-title">健康提醒</div>
            <div class="action-desc">设置健康数据记录提醒</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <el-dialog v-model="dialogVisible" title="添加健康记录" width="500px">
      <health-record-form @record-added="handleRecordAdded" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus, List, AlarmClock } from '@element-plus/icons-vue'
import HealthRecordForm from './components/HealthRecordForm.vue'

const router = useRouter()
const dialogVisible = ref(false)
const visibleHealthData = ref([])

// 获取当前用户ID
let userId = null
const userInfoStr = localStorage.getItem('userInfo')
const userStr = localStorage.getItem('user')

if (userInfoStr) {
  try {
    userId = JSON.parse(userInfoStr).id
    console.log('从userInfo获取到用户ID:', userId)
  } catch (e) {
    console.error('解析userInfo失败:', e)
  }
} else if (userStr) {
  try {
    userId = JSON.parse(userStr).id
    console.log('从user获取到用户ID:', userId)
  } catch (e) {
    console.error('解析user失败:', e)
  }
}

if (!userId) {
  // 如果都没有获取到，默认使用ID为8用于测试
  userId = 8
  console.log('未找到用户信息，使用默认ID:', userId)
}

// 获取用户可见的健康数据总览
const getHealthOverview = async () => {
  if (!userId) return
  
  try {
    // 尝试从本地存储获取数据
    const localData = localStorage.getItem(`health_overview_${userId}`)
    if (localData) {
      visibleHealthData.value = JSON.parse(localData)
      console.log('从本地存储加载健康数据总览:', visibleHealthData.value)
      return
    }
    
    // 尝试调用API但预期会失败，直接使用演示数据
    loadDemoData()
    
    // 保存演示数据到本地存储
    localStorage.setItem(`health_overview_${userId}`, JSON.stringify(visibleHealthData.value))
  } catch (error) {
    console.error('获取健康数据总览失败', error)
    // 接口异常，使用模拟数据
    loadDemoData()
    // 保存演示数据到本地存储
    localStorage.setItem(`health_overview_${userId}`, JSON.stringify(visibleHealthData.value))
  }
}

// 加载演示数据
const loadDemoData = () => {
  visibleHealthData.value = [
    {
      typeId: 1,
      typeName: '血压(收缩压)',
      lastValue: '125',
      unit: 'mmHg',
      lastDate: '今天 08:30',
      isAbnormal: false
    },
    {
      typeId: 2,
      typeName: '血压(舒张压)',
      lastValue: '85',
      unit: 'mmHg',
      lastDate: '今天 08:30',
      isAbnormal: false
    },
    {
      typeId: 3,
      typeName: '心率',
      lastValue: '78',
      unit: '次/分钟',
      lastDate: '今天 08:30',
      isAbnormal: false
    },
    {
      typeId: 4,
      typeName: '血糖(空腹)',
      lastValue: '6.2',
      unit: 'mmol/L',
      lastDate: '今天 07:00',
      isAbnormal: true
    },
    {
      typeId: 6,
      typeName: '体重',
      lastValue: '65.5',
      unit: 'kg',
      lastDate: '昨天 20:00',
      isAbnormal: false
    }
  ]
}

// 英文健康类型名称翻译为中文
const translateTypeName = (engName) => {
  const typeMap = {
    'Blood Pressure (Systolic)': '血压(收缩压)',
    'Blood Pressure (Diastolic)': '血压(舒张压)',
    'Heart Rate': '心率',
    'Blood Glucose (Fasting)': '血糖(空腹)',
    'Blood Glucose (2h Postprandial)': '血糖(餐后2小时)',
    'Weight': '体重',
    'Body Temperature': '体温',
    'Sleep Duration': '睡眠时间',
    'Medication Record': '用药记录',
    'Dietary Record': '饮食记录'
  }
  return typeMap[engName] || engName
}

// 根据类型ID获取图标样式
const getTypeIcon = (typeId) => {
  const iconMap = {
    1: 'iconfont icon-blood-pressure',
    2: 'iconfont icon-blood-pressure',
    3: 'iconfont icon-heart-rate',
    4: 'iconfont icon-blood-glucose',
    5: 'iconfont icon-blood-glucose',
    6: 'iconfont icon-weight',
    7: 'iconfont icon-temperature',
    8: 'iconfont icon-sleep',
    9: 'iconfont icon-medication',
    10: 'iconfont icon-diet'
  }
  return iconMap[typeId] || 'el-icon-data-analysis'
}

// 跳转到记录健康数据页面
const goToRecord = () => {
  router.push('/front/health/record')
}

// 跳转到健康数据历史页面
const goToHistory = () => {
  router.push('/front/health/history')
}

// 跳转到健康提醒设置页面
const goToReminder = () => {
  router.push('/front/health/reminder')
}

// 处理健康记录添加成功事件
const handleRecordAdded = () => {
  dialogVisible.value = false
  getHealthOverview() // 刷新数据
  ElMessage.success('健康记录添加成功')
  
  // 更新本地存储
  localStorage.setItem(`health_overview_${userId}`, JSON.stringify(visibleHealthData.value))
}

onMounted(() => {
  getHealthOverview()
})
</script>

<style scoped>
.health-home-container {
  padding: 20px;
}

.health-home-title {
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
  font-weight: 500;
}

.health-overview {
  margin-bottom: 40px;
}

.health-card {
  height: 160px;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.health-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.abnormal-card {
  border-left: 4px solid #F56C6C;
}

.health-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.health-type {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
}

.type-icon {
  margin-right: 10px;
  font-size: 20px;
  color: #409EFF;
}

.health-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.unit {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
}

.health-date {
  font-size: 12px;
  color: #909399;
}

.health-actions {
  margin-top: 40px;
}

.action-card {
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.action-icon {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 15px;
}

.action-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.action-desc {
  font-size: 14px;
  color: #909399;
  text-align: center;
}

.empty-data-container {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
}

@media screen and (max-width: 768px) {
  .health-home-container {
    padding: 10px;
  }
  
  .el-col {
    width: 100% !important;
  }
}
</style> 